<template>
  <div class="box">
    <header class="header">
         <van-nav-bar :title="cartsNum > 0 ? '购物车(' + cartsNum + ')' : '购物车' " left-arrow @click-left="$router.back()">
      </van-nav-bar>
    </header>
    <div class="content">
      <div class="noShop" v-if="empty">
        <van-empty
          image="https://img1.baidu.com/it/u=812865506,616477484&fm=253&fmt=auto&app=120&f=JPEG"
          description="购物车空空如也">
          <van-button round type="danger" @click="$router.push('/homeIndex')" class="bottom-button">立即购买</van-button>
        </van-empty>
      </div>
      <div class="hasShop" v-else>
        <van-swipe-cell v-for="item of cartList" :key="item.cartid">
          <van-row>
            <van-col span="2" class="checkBox">
              <van-checkbox v-model="item.flag" @click="updateFlag(item.cartid, item.flag)"></van-checkbox>
            </van-col>
            <van-col span="22">
              <van-card
                :price="item.originprice"
                :title="item.proname"
                :thumb="item.img1"
              >
                <template #num>
                  <van-stepper v-model="item.num" theme="round" button-size="22" @change="updateCartNum(item.cartid, item.num)"/>
                </template>
              </van-card>
            </van-col>
          </van-row>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="delCartById(item.cartid)" />
          </template>
        </van-swipe-cell>
      </div>
      <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="checked" @click="selectAll">全选</van-checkbox>
      </van-submit-bar>
       <van-divider>猜你喜欢</van-divider>
      <pro-list :list="recommendList"></pro-list>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Card, Stepper, Checkbox, CheckboxGroup, SwipeCell, Button, Row, Col, Toast, Empty, SubmitBar, Divider } from 'vant'
import { getCartList, remove, updateNum, selectall, selectone, getRecommendList } from '@/api/carts'
import { addOrder } from '@/api/order'
import ProList from './../../components/proList'
import { mapMutations, mapState } from 'vuex'

Vue.use(NavBar)
Vue.use(Card)
Vue.use(Stepper)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(SwipeCell)
Vue.use(Button)
Vue.use(Row)
Vue.use(Col)
Vue.use(Toast)
Vue.use(Empty)
Vue.use(SubmitBar)
Vue.use(Divider)
export default {
  components: {
    ProList
  },
  data () {
    return {
      cartList: [],
      recommendList: [],
      empty: false,
      checked: false
    }
  },
  computed: {
    totalPrice () {
      return this.cartList.reduce((sum, item) => {
        return item.flag ? sum + item.num * item.originprice : sum + 0
      }, 0) * 100
    },
    ...mapState({
      cartsNum: state => state.carts.cartsNum
    })
  },
  async mounted () {
    var isLogin = localStorage.getItem('isLogin')
    if (isLogin === 'true') {
      this.getCartList()
    } else {
      this.$router.push({ path: 'login' })
    }
    getRecommendList().then(res => {
      this.recommendList = res.data.data
    })
  },
  methods: {
    ...mapMutations({ // 在当前的组件中生成changeIsLogin函数，实际上就是this.$store.commit('changeIsLogin', false)
      changeCartsNum: 'carts/changeCartsNum' // 按照模块操作
    }),
    async getCartList () {
      var carts = await getCartList({
        userid: localStorage.getItem('userid')
      })
      if (carts.data.code === '10020') {
        this.empty = true
      } else {
        this.empty = false
        this.cartList = carts.data.data
        this.changeCartsNum(this.cartList.length)
        this.checked = this.cartList.every(item => item.flag)
      }
    },
    async delCartById (cartid) {
      var res = await remove({ cartid })
      if (res.data.code === '200') {
        Toast('删除成功')
        this.getCartList()
      } else {
        Toast('删除失败')
      }
    },
    async updateCartNum (cartid, num) {
      var res = await updateNum({ cartid: cartid, num: num })
      console.log(res)
      if (res.data.code === '200') {
        this.getCartList()
      }
    },
    async onSubmit () {
      var res = await addOrder({
        userid: localStorage.getItem('userid')
      })
      if (res.data.code === '200') {
        Toast('订单添加成功')
        var orderTime = res.data.time
        this.$router.push({ path: 'order', query: { time: orderTime } })
      } else {
        Toast('订单添加失败')
      }
    },
    async selectAll () {
      var res = await selectall({
        userid: localStorage.getItem('userid'),
        type: this.checked
      })
      if (res.data.code === '200') {
        this.getCartList()
      }
    },
    async updateFlag (cartid, flag) {
      var res = await selectone({
        cartid: cartid,
        flag: flag
      })
      if (res.data.code === '200') {
        this.getCartList()
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
 .goods-card {
    margin: 0;
    background-color: @white;
  }

  .delete-button {
    height: 100%;
  }

.checkBox
  display flex
  justify-content center
  align-items center
  height 100%
  background-color #fff
  .van-checkbox
    position absolute
    top 50%
    transform translateY(-50%)

.van-row
  background-color #fff
.van-card
  background-color #fff

.noShop
 display flex
 justify-content center
 align-items center

</style>
